package com.qp.basics.estivate.support;

import com.qp.basics.estivate.ConnectionProvider;
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.naming.NamingException;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * 基于驱动的链接提供类。
 *
 *
 */
public class DriverConnectionProvider implements ConnectionProvider {
	private static Log log = LogFactory.getLog(DriverConnectionProvider.class);

	private String url;
	private String user;
	private String password;
	private String driver;
	private BasicDataSource dataSource = null;
	 
	
	
	/**
	 * 
	 * @return
	 * @throws SQLException
	 * @throws NamingException
	 * @throws ClassNotFoundException
	 */
	public final Connection getConnection() {

		if(dataSource == null){
			dataSource = new BasicDataSource();
			dataSource.setDriverClassName(driver);
			dataSource.setUsername(user);
			dataSource.setPassword(password);
			dataSource.setUrl(url); 
//			dataSource.setMaxIdle(2);
			dataSource.setMaxActive(5);
			dataSource.setMaxWait(10*1000);
			dataSource.setRemoveAbandoned(true);
			dataSource.setRemoveAbandonedTimeout(5);
			dataSource.setLogAbandoned(true);
		}
		Connection conn = null;
		
		try {
			conn = dataSource.getConnection();
		} catch (SQLException e) {			
			log.error("Retrieve a connection", e);
		}
		 
		return conn;

	}

	public void closeConnection(Connection conn) throws SQLException {
		conn.close();
	}

	public String getDriver() {
		return driver;
	}

	public void setDriver(String driver) {
		this.driver = driver;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getUser() {
		return user;
	}

	public void setUser(String user) {
		this.user = user;
	}

}
